//
//  KATBannerData.m
//  KATFramework
//
//  Created by Kantice on 15/9/11.
//  Copyright (c) 2015年 KatApp. All rights reserved.
//

#import "KATBannerData.h"
#import "KATImage.h"



@implementation KATBannerData



+ (instancetype)bannerData
{
    return [[[self alloc] init] autorelease];
}


//初始化
- (instancetype)init
{
    self=[super init];
    
    self.type=0;
    self.num=0;
    self.tag=0;
    self.index=0;
    self.value=0.0;
    self.message=nil;
    self.url=nil;
    self.object=nil;
    self.state=0;
    self.title=nil;
    self.indicator=KATButtonTypeFilledRound;
    self.imagePath=nil;
    self.hasTitleColor=NO;
    self.titleColor=nil;
    self.isRemoteImage=NO;
    self.isCacheImage=NO;
    self.isImageReady=NO;
    self.isLoadImageFail=NO;
    
    return self;
}


//设置图片
- (void)setImagePath:(NSString *)imagePath
{
    if(_imagePath!=imagePath)
    {
        [_imagePath release];
        
        _imagePath=[imagePath copy];
        
        if(_imagePath)
        {
            _isImageReady=YES;
        }
    }
}



//远程加载图片（异步）
- (void)loadRemoteImageWithSavePath:(NSString *)path andUrl:(NSString *)url
{
    //设置标识量
    _isRemoteImage=YES;
    _isCacheImage=YES;
    _isLoadImageFail=NO;
    _isImageReady=NO;
    
    //先判断是否本地已保存该图片
    if([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:false])//存在该文件，则不需要下载
    {
        self.imagePath=path;
    }
    else//不存在该文件，则去下载
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^
        {
           _isLoadImageFail=!([KATHttpUtil downloadFile:path fromUrl:url]);
                       
           if(!_isLoadImageFail)//下载成功
           {
               self.imagePath=path;
           }
           else if([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:false])//如果已经存在该图片（其他线程下载）
           {
               _isLoadImageFail=NO;
           }
           
           _isImageReady=YES;            
        });
    }
}


//远程加载图片（异步，使用KATImage的）
- (void)loadRemoteImageWithUrl:(NSString *)url
{
    [self loadRemoteImageWithSavePath:[NSString stringWithFormat:@"%@/%@",KATImage.cacheDir,[KATImage fileNameWithUrl:url]] andUrl:url];
}


//描述
- (NSString *)description
{
    return [NSString stringWithFormat:@"KATBannerData(%i) : %@!",_num,_title];
}


- (void)dealloc
{
//    NSLog(@"%@ is dealloc!",self);
    
    [_message release];
    [_object release];
    [_url release];
    [_title release];
    [_imagePath release];
    [_titleColor release];
    
    [super dealloc];
}

@end
